<template>
  <div class="materialClassAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(materialClassFormRef)"
        v-preventReClick
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item name="1" class="transform-down">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType === "detail" ? "" : pageType === "add" ? "新增" : "编辑"
            }}物料分类信息</span
          >
        </template>
        <div class="materialClass-info">
          <el-form
            :model="materialClassForm"
            ref="materialClassFormRef"
            :rules="queryRules"
            label-width="100"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="分类名称：" prop="categoryName">
                  <el-input
                    ref="refInput"
                    v-model="materialClassForm.categoryName"
                    placeholder="请输入"
                    clearable
                    maxlength="20"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="是否有下级分类："
                  prop="childCategory"
                  label-width="140"
                >
                  <el-select
                    v-model="materialClassForm.childCategory"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleChildCategory"
                  >
                    <el-option
                      v-for="dict in flagList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7" v-if="materialClassForm.childCategory === 0">
                <el-form-item
                  label="是否属于贵重设备："
                  prop="importantDevice"
                  label-width="160"
                >
                  <el-select
                    v-model="materialClassForm.importantDevice"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                  >
                    <el-option
                      v-for="dict in flagList"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addMaterialClass,
  editMaterialClass,
  getMaterialClassApi,
} from "@/api/information/materialClass";
const emit = defineEmits([
  // 物料分类新增组件显隐
  "materialClassAddShow",
  // 更新物料分类新增组件显隐
  "update:materialClassAddShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
  materialClassList: {
    type: Array,
    default: [],
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 物料分类表单引用
const materialClassFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 物料分类表单数据模板
const materialClassFormTemplate = {
  categoryName: "",
  childCategory: null,
  importantDevice: null,
  parentId: null,
};

//是否有下级分类自定义校验
const isSubordinate = (rule, value, callback) => {
  if (
    value == 0 &&
    rowitem &&
    rowitem.children &&
    rowitem.children.length != 0
  ) {
    callback(new Error("该分类有下级分类，请删除下级分类后再修改此选项"));
  } else {
    callback();
  }
};
//防重复校验
const categoryNamevalidator = (rule, value, callback) => {
  if (props.pageType != "edit") {
    let flag = props.materialClassList.find((element) => {
      return element.categoryName == value;
    });
    if (flag) {
      callback(new Error("不能重复添加重复的名字"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const data = reactive({
  // 物料分类表单
  materialClassForm: JSON.parse(JSON.stringify(materialClassFormTemplate)),
  // 物料分类表单校验规则
  queryRules: {
    categoryName: [
      { required: true, message: "请输入分类名称", trigger: "blur" },
      { validator: categoryNamevalidator, trigger: "change" },
    ],
    childCategory: [
      { required: true, message: "请选择是否有下级分类", trigger: "change" },
      { validator: isSubordinate, trigger: "change" },
    ],
    importantDevice: [
      { required: true, message: "请选择是否属于贵重设备", trigger: "change" },
    ],
  },
  // 是否选项列表
  flagList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
});
const { materialClassForm, queryRules, flagList } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} materialClassFormRef 物料分类表单引用
 */
const handleAddSave = async (materialClassFormRef) => {
  if (!materialClassFormRef) return;
  await materialClassFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const apiFunc = materialClassForm.value.categoryId
            ? editMaterialClass
            : addMaterialClass;

          const res = await apiFunc(materialClassForm.value);
          if (res.code === 200) {
            emit("update:materialClassAddShow", false);
            emit("refreshList", false);
            ElMessage.success(res.msg);
            materialClassForm.value = JSON.parse(
              JSON.stringify(materialClassFormTemplate)
            );
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail") {
    emit("update:materialClassAddShow", false);
    materialClassForm.value = JSON.parse(
      JSON.stringify(materialClassFormTemplate)
    );
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:materialClassAddShow", false);
        materialClassForm.value = JSON.parse(
          JSON.stringify(materialClassFormTemplate)
        );
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
let rowitem = null; //编辑点击进来的row
const handleDetailInfo = async (row) => {
  try {
    rowitem = row;
    detailInfoShow.value = true;
    const res = await getMaterialClassApi(row.id);
    materialClassForm.value = res.data;
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理父组件id
 * @param {Number} id
 */
const handleParentId = (id) => {
  materialClassForm.value.parentId = id;
};

/**
 * @description: 处理是否有下级分类改变
 */
const handleChildCategory = () => {
  materialClassForm.value.importantDevice = null;
};

onMounted(() => {
  nextTick(() => {
    refInput.value.focus();
  });
});

defineExpose({
  handleDetailInfo,
  handleParentId,
});
</script>
<style lang="scss" scoped>
.materialClassAdd {
  padding: 20px;
  width: 100%;
  height: 100%;
  .materialClass-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  :deep(.el-select .el-input__wrapper) {
    height: 34px;
  }
}
</style>
